<template>
  <div class="app-container">

    <!--总揽：
    1-搜索框
    2-表格
    3-分页插件条
    4-隐藏页面-“新增”/“编辑” 弹窗
    5-隐藏页面-“删除” 弹窗
    -->

    <!--  1-搜索框    -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">

        <!--条件框1、根据状态筛选-->
        <el-form-item>
          <el-select v-model="experimentType" clearable placeholder="实验类型" @change="doTypeFilter()">
            <el-option
              v-for="item in type"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      <!--</el-form>-->
        <!--&lt;!&ndash;条件框2、根据命名筛选&ndash;&gt;-->
      <!--<el-form :inline="true" >-->
      <el-form-item>
          <el-input   placeholder="姓名" v-model="searchName"></el-input>
        </el-form-item>

        <!--“搜索”按钮-->
        <el-form-item>
          <el-button type="primary" @click="doNameFilter()"><i class="el-icon-search"></i>搜索</el-button>
        </el-form-item>

        <!--“新增”按钮-->
        <el-form-item>
          <el-button type="primary" @click="addUpdate()">新增</el-button>
        </el-form-item>

        <!-- "导出"按钮 -->
        <el-form-item>
          <el-button style='margin:0 0 20px 20px;' type="primary" icon="document" @click="handleDownload" :loading="downloadLoading">{{$t('excel.export')}} excel</el-button>
        </el-form-item>

      </el-form>
    </el-col>


    <div>

      <div style="float:left; width: 50%;">
        <el-col :span="6" style="width: 100%;height: 100%">

            <img :src="this.GLOBAL.shot.imgUrl" style="max-width: 90%; max-height: 100%; width: 2000px">

        </el-col>
      </div>

      <div style="float:right; width: 50%;">

        <!-- 2-列表     -->
        <!--列表示例数据，目前有total 和 rows两个字段，  以后会加其他；
        {
        "total": 4,

        "rows": [
        {
        "fieldId": "field2",
        "deleted": false,
        "name": "加工鉴定",
        "experimentName": "process_identify",
        "shotId": "shot1",
        "rowAmount": 30,
        "columnAmount": 5,
        "remark": "三行两重复，每行5株。"
        },
        {
        "fieldId": "field3",
        "deleted": false,
        "name": "早熟预备比-M",
        "experimentName": "earlymaturing_preparation",
        "shotId": "shot1",
        "rowAmount": 20,
        "columnAmount": 4,
        "remark": "2行三重复，每行5株。"
        }
        ]
        }
        -->

        <el-table :data="tableList" max-height="550" v-loading="listLoading"   border element-loading-text="拼命加载中" style="width: 100%;">
          <!--1）第一列，-->
          <el-table-column prop="fieldId" label="试验田序号"> </el-table-column>
          <!--2) 第二列-->
          <el-table-column prop="name" label="试验田名称"> </el-table-column>

          <el-table-column prop="experimentName" label="试验类型"> </el-table-column>

          <!--总示例太多，故注释掉一部分
          <el-table-column prop="title" min-width="150px" label="标题">
          </el-table-column>
          <el-table-column prop="number" label="阅读数" width="65">
          </el-table-column>
          <el-table-column prop="date" label="时间" width="110px">
          </el-table-column>

          <el-table-column label="状态" width="120">
            <template slot-scope="scope">
              <el-tag size="small" :type="scope.row.status | statusFilter" @click="isStatus(scope.$index, scope.row)"
                      v-if="scope.row.status == 1">启用
              </el-tag>
              <el-tag size="small" :type="scope.row.status | statusFilter" @click="isStatus(scope.$index, scope.row)"
                      v-if="scope.row.status == 2">禁用
              </el-tag>
            </template>
          </el-table-column>
          -->

          <!-- 3） 第三列 自定义列；"operation"为列表中没有的字段；    -->
          <el-table-column prop="operation" label="操作 ">
            <!--把遍历列表中取出的每一项命名为“scope”；它包含“row”、“$index”两个字段，“row”中就是列表中的一项，“$index”应该是框架自动给加的编号-->
            <template slot-scope="scope">

              <!--操作1、编辑项目，显示编辑条目弹窗-->
              <el-button size="small" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>

              <!--操作2、 进入跳转到field的详情，即plotList页面-->
              <el-button  size="mini" type="success" @click="getInPlotList(scope.row)">进入</el-button>

              <!--操作3、  删除项目，显示删除弹窗-->
              <el-button size="small" type="danger" @click="deleteUpdate(scope.row)">删除</el-button>

              <!--&lt;!&ndash;操作4.1、与操作4.2 二选一显示；    &ndash;&gt;-->
              <!--<el-button v-if="scope.row.status!='2'" size="mini" type="success" @click="handleModifyStatus(scope.row,'2')">启用</el-button>-->
              <!--&lt;!&ndash;操作4.2、与操作4.1  二选一显示；    &ndash;&gt;-->
              <!--<el-button v-if="scope.row.status!='1'" size="mini" @click="handleModifyStatus(scope.row,'1')">禁用</el-button>-->

            </template>
          </el-table-column>

        </el-table>

        <!--  3-分页插件的工具条                 -->
        <el-pagination layout="total, prev, pager, next"
                       background
                       :page-size="10"
                       @size-change="handleSizeChange"
                       :total="total"
                       @current-change="handleCurrentChange"
                       style="text-align:center;">
        </el-pagination>


      </div>
    </div>

    <!-- 4-隐藏页面-编辑field信息弹窗                      -->
    <el-dialog title="Edit" :visible.sync="isShowEditVisible">

      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="Field名称" prop="fieldName">
          <el-input v-model="farmlandMsg.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="farmlandMsg.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowEditVisible = false">取消</el-button>
        <el-button type="primary" :loading="listLoading" @click="updateData( farmlandMsg)" class="title1">确定</el-button>
      </div>

    </el-dialog>

    <!-- 5-新增Field弹窗详情 -->
    <el-dialog title="新增" :visible.sync="isShowAddVisible">

      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="名字" prop="name">
          <el-input v-model="farmlandMsg.name"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="实验类型" prop="experimentName">
          <el-form-item>
            <el-select v-model="experimentType" clearable placeholder="实验类型">
              <el-option
                v-for="item in type"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="shotId" prop="shotId">
          <el-input v-model="farmlandMsg.shotId"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="行数" prop="rowAmount">
          <el-input v-model="farmlandMsg.rowAmount"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="列数" prop="columnAmount">
          <el-input v-model="farmlandMsg.columnAmount"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="farmlandMsg.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddVisible = false">取消</el-button>
        <el-button type="primary" :loading="listLoading" @click="submitAdd(farmlandMsg)" class="title1">确定</el-button>
      </div>

    </el-dialog>

    <!-- 6-隐藏页面-删除弹框                           -->
    <el-dialog title="删除" :visible.sync="deleteVisible" width="30%">
      <span>确认删除吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>


<script>
  // 把getFieldList接口导入进来；
  import { getFieldList,editField,addField,deleteField } from '@/api/FarmlandManage'
  import { getExperimentTypes } from '../../api/FarmlandManage'
  import { parseTime } from '../../utils'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'

  /* 内含主要3部分：
  * 1、页面属性，位于data()中；
  * 2、页面初始化方法，位于created()中；
  * 3、页面方法，位于methods()中；
  *  */

  export default{

    // 一、表示属于该页面的成员属性，
    data() {
      return {

        listLoading: true, // 等待数据加载时的动画；
        downloadLoading: false, // 等待下载excel时的动画
        filename: '', // 列表导出为excel的文件名
        autoWidth: true,
        list: null,

        tableList: [], // 列表中的数据；
        total: 0,
        page: 1,
        pageSize: 10,
        filterTableDataEnd: [] , // 这个demo项目中，前端也会对后端取到的list数据进行筛选，这里存放前端筛选后的数据；
        sels: [], // 列表选中列
        filter: {
          key: '',
        },

        status: [       // 筛选条件下拉框列表项：1-启用，2-禁用；
          {
            statusId: 1,
            label: '启用'
          }, {
            statusId: 0,
            label: '禁用'
          }
        ],

        value: '', // 筛选条件： 启用/禁用
        searchName: '', // 筛选条件： 姓名

        isShowEditVisible: false, // “编辑field”弹窗
        deleteVisible: false, // “删除field”弹窗
        isShowAddVisible: false, // "添加field"弹窗按钮

        temp: { // 编辑条目时， “编辑”弹窗中数据的存放位置；“新增”弹窗同理。
          uid: '',
          cname: '',
          date: '',
          status: ''
        },

        farmlandMsg: {
          name: '',
          remark: '',
          experimentName: '',
          shotId: '',
          rowAmount: '',
          columnAmount: '',
        },

        type: [],
        experimentType: '',
        fieldId: '',
        fieldId1: ''

      }
    },

    //二、类似于构造方法；
    created() {
      this.fetchData()
     // for (var i=0;i<=20;i++) {
     // this.type = this.getExperimentTypes().response.data.rows
      getExperimentTypes().then(response => {
        this.type = response.data.rows
        //this.$message.warning(this.getExperimentTypes().response.data.rows)
      })
    },

    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },

    //三、页面中的成员方法
    methods: {
      // 列表导出为excel
      handleDownload() {
        this.downloadLoading = true
        const date = new Date()
        //this.filename = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + '-' + date.getHours() + '-' + date.getMinutes()
        this.filename = date.getFullYear()
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['fieldId','fieldName', 'experimentName']
          const filterVal = ['fieldId', 'name', 'experimentName']
          const list = this.tableList
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      addUpdate() {
        this.isShowAddVisible = true
      },
      //查看field内所含的plot信息，即进入plotList页面；
      getInPlotList(field) {
        this.GLOBAL.field = field   //在全局变量中记录当前欲进入的field，方便field信息页面知道该加载哪个field的初始化信息；
        this.$router.push("/field")  //路由跳转到field页面；
      },

      fetchData() {
        this.listLoading = true
        getFieldList({'shotId': this.GLOBAL.shot.shotId}).then(response => {
          const limit = 10
          //  在前端做的一个分页查询，显示部分数据；
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          this.total = response.data.total
          this.tableList = pageList
          this.listLoading = false
        })
      },
      submitAdd(farmlandMsg) {
        addField({'name':this.farmlandMsg.name,'experimentName': this.farmlandMsg.experimentName,'shotId':this.farmlandMsg.shotId
        ,'rowAmount':this.farmlandMsg.rowAmount,'columnAmount':this.farmlandMsg.columnAmount,'remark': this.farmlandMsg.remark}).then(response => {
          this.fetchData()
        })

        this.isShowAddVisible = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      },
      // 类别检索
      doTypeFilter() {
        this.listLoading = true
        getFieldList({ 'shotId': this.GLOBAL.shot.shotId, 'experimentName': this.experimentType }).then(response => {
          const limit = 10
          // 居然在前端做筛选，牛逼！
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          // console.log(pageList)
          this.total = response.data.total
          this.tableList = pageList
          this.listLoading = false
        })
      },

      // 名称检索
      doNameFilter() {
        if (this.searchName === '') {
          this.fetchData()
          this.$message.warning('查询条件不能为空！')
          return
        }

        this.listLoading = true
        getFieldList({ 'shotId': this.GLOBAL.shot.shotId, 'fieldName': this.searchName }).then(response => {
          const limit = 10
          // 居然在前端做筛选，牛逼！
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          // console.log(pageList)
          this.total = response.data.total
          this.tableList = pageList
          this.listLoading = false
        })
      },
      clickfun(e) {
        console.log(e.target.innerText)
      },

      handleUpdate(row) {
        this.isShowEditVisible = true
        this.temp = Object.assign({}, row)
        console.log(row)
        this.fieldId = row.fieldId
      },

      deleteUpdate(row) {
        console.log(row)
        this.deleteVisible = true
        this.temp = Object.assign({}, row)
        this.fieldId1 = row.fieldId
        // console.log(row)
      },

      submitDelete() {
        // const tempData = Object.assign({}, this.temp)
        // console.log(tempData)
        // console.log(this.tableList)
        // for (const v of this.tableList) {
        //   if (v.uid === this.temp.uid) {
        //     const index = this.tableList.indexOf(v)
        //     this.tableList.splice(fieldList, 1)
        //     this.fetchData()
        //     console.log(this.tableList)
        //     break
        //   }
        // }
        deleteField({ 'fieldId': this.fieldId1 }).then(response => {
          this.fetchData()
        })
        this.deleteVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      },

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        console.log(row)
        row.status = status
      },

      updateData( farmlandMsg ) {
        // const tempData = Object.assign({}, this.temp)
        // console.log(tempData)
        // updateArticle(tempData).then(() => {
        //   for (const v of this.tableList) {
        //     if (v.uid === this.temp.uid) {
        //       const index = this.tableList.indexOf(v)
        //       this.tableList.splice(fieldList, 1, this.temp)
        //       break
        //     }
        //   }
        //   this.isShowEditVisible = false
        //   this.$notify({
        //     title: '成功',
        //     message: '更新成功',
        //     type: 'success',
        //     duration: 2000
        //   })
        // })

        editField({'fieldId': this.fieldId, 'name': farmlandMsg.name,'remark': farmlandMsg.remark}).then(response => {
          this.fetchData()
        })
        this.isShowEditVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      },

      handleSizeChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      handleCurrentChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      currentChangePage(list) {
        let from = (this.page - 1) * this.pageSize
        const to = this.page * this.pageSize
        this.tableList = []
        for (; from < to; from++) {
          if (list[from]) {
            this.tableList.push(list[from])
          }
        }
      }

    }
  }

</script>
